using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Timers;
using System.Collections;

namespace monoServer
{
	public class Client : Form
	{
		private LoginWindow loginWindow;
		private MainWindow mainWindow;
		
		private Configuration conf;
		private DataManager dm;
		private CommunicatorParallel c;
		private Cron cron;
		private ThreadManager tm;
		private ulong workerThreadID;
		
		public static void Main()
		{
			Client c = new Client();			
		}
		
		public Client ()
		{
			this.setup();
			Application.Run(this.loginWindow);
		}
		
		public void start()
		{
			while(true)
			{
				if(this.c.responseQueue.Count > 0)
				{
					//Console.WriteLine("count > 0");
					Telegram tres = (Telegram)this.c.responseQueue.Dequeue();
					Telegram treq = Telegram.Parse((string)((ArrayList)this.c.sendTelegrams.selectRow("id", tres[0]))[4]);
					switch(treq.keyWord)
					{
					case "LOGIN":
						//Console.WriteLine("login");
						if(tres[1].Equals("OK"))
						{
							//Console.WriteLine("ok");
							this.loginWindow.Hide();
							this.mainWindow.Show();
						} else {
							//Console.WriteLine("nok");
							this.loginWindow.resetFormular();
							this.loginWindow.setErrorMsg(tres[2]);
						}
						break;
					}
				}
			}
		}
		
		private void setup()
		{
			this.conf = new Configuration(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/.monoclient/.config");
			this.conf.values["logdir"] = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/" + (string)this.conf.values["logdir"];
			this.conf.values["logdirt"] = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/" + (string)this.conf.values["logdirt"];
			
			this.dm = new DataManager();
					
			this.c = new CommunicatorParallel(new TcpClient((string)this.conf.values["server_ip"],int.Parse((string)this.conf.values["server_port"])), this.dm, new Logger(this.conf));
			
			this.cron = new Cron();
			this.cron.addJob("sendping", new ElapsedEventHandler(this.c.sendPing),int.Parse((string)this.conf.values["send_ping_time"]));
			this.cron.startJob("sendping");
			
			this.loginWindow = new LoginWindow(250, 200);
			this.loginWindow.btn_login.Click += new EventHandler(this.sendLogin);
			this.mainWindow = new MainWindow(500, 500);
			
			
			this.tm = new ThreadManager(5, this.dm);
			this.workerThreadID = this.tm.getNewThread(this.start);
			this.tm.startThread(this.workerThreadID);
		
		}
		
		private void sendLogin(object sender, EventArgs e)
		{
			/*
			Telegram t = new Telegram("LOGIN", Telegram.REQUEST, this.dm.currentTelegramKey);
			t.addParameter(this.loginWindow.userName);
			t.addParameter(DataManager.getMD5(this.loginWindow.userPassword));
			*/
			Telegram t = Telegram.getRequest(this.dm.currentTelegramKey, "LOGIN", this.loginWindow.userName, DataManager.getMD5(this.loginWindow.userPassword));
			this.c.sendTelegram(t);
		}
	}
}

